package com.zlm.pc;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @Author: 郑
 * 使用lock实现生产者消费者
 */
public class PcDemo2 {
    public static void main(String[] args) {
        Data2 data2 = new Data2();
        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                data2.increment();
            }
        },"a").start();
        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                try {
                    data2.decrement();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"b").start();

    }
}

class Data2{
    private int num = 0;
    //锁
    final Lock lock = new ReentrantLock();

    Condition condition = lock.newCondition();

    public void increment(){
        lock.lock();

        try {
            if(num !=0){
                //等待
                condition.await();
            }
            //业务
            num++;
            System.out.println(Thread.currentThread().getName()+"=>"+num);
            //通知
            condition.signalAll();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }


    }

    public void decrement() throws InterruptedException {
        lock.lock();
        if(num != 1){
            //等待
            condition.await();
        }
        //业务
        num--;
        System.out.println(Thread.currentThread().getName()+"=>"+num);
        //通知
        condition.signalAll();
    }
}
